/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.servlets;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hibernate.Session;
import ru.miit.elearning.hibernate.dao.HibernateUtil;
import ru.miit.elearning.hibernate.dto.Document;
import ru.miit.elearning.hibernate.dto.DocumentContent;
import ru.miit.elearning.hibernate.dto.DocumentContentId;

/**
 *
 * @author Cyclone
 */
public class UploadServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        InputStream uploadedStream = null;

        Session session = null;

        try {

            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            // TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet UploadServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet UploadServlet at " + request.getContextPath() + "</h1>");

            /*
            out.println("<p>Attributes</p>");
            out.println("anything attribute = " + request.getAttribute("anything"));
            Enumeration<String> attrEnum = request.getAttributeNames();
            while (attrEnum.hasMoreElements()) {
            out.print("Attribute = " + attrEnum.nextElement()+"<br/>");
            }

            out.println("<p>Parameters</p>");
            out.println("anything parameter = " + request.getParameter("anything"));
            Enumeration<String> parEnum = request.getParameterNames();
            while (parEnum.hasMoreElements()) {
            out.print("Parameter = " + parEnum.nextElement()+"<br/>");

            }
             */

            out.println("<p><a href=\"file.html\">file.html</a></p>");

            // Check that we have a file upload request
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            System.out.println("isMultipart = " + isMultipart);

            if (isMultipart) {
                // Create a factory for disk-based file items
                FileItemFactory factory = new DiskFileItemFactory();
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                // Parse the request
                List<FileItem> items = upload.parseRequest(request);
                FileItem fileItem = null;




                Integer docId = null;
                for (FileItem item : items) {
                    System.out.println("processing item");

                    // Process a regular form field
                    if (item.isFormField()) {
                        String name = item.getFieldName();
                        String value = item.getString();

                        if (name.equalsIgnoreCase("docId")) {
                            docId = Integer.parseInt(value);
                        }

                        //System.out.println("name = " + name);
                        //System.out.println("value = " + value);
                    }

                    if (!item.isFormField()) {
                        fileItem = item;
                    }
                }

                if (fileItem != null) {
                    String fieldName = fileItem.getFieldName();
                    String fileName = fileItem.getName();
                    String contentType = fileItem.getContentType();
                    boolean isInMemory = fileItem.isInMemory();
                    long sizeInBytes = fileItem.getSize();

                    // ...
                    System.out.println("fileName = " + fileName);
                    System.out.println("contentType = " + contentType);
                    System.out.println("isInMemory = " + isInMemory);
                    System.out.println("sizeInBytes = " + sizeInBytes);

                    uploadedStream = fileItem.getInputStream();
                    //uploadedStream.
                    //...

                    /*
                    Document doc = new Document();
                    doc.setTitle("Test file");
                     */
                    if (docId == null) {
                        docId = 1;
                    }
                    //(Integer) session.save(doc);

                    int version = 1 + ((Document)session.get(Document.class, docId)).getCurrentVersionContent().getId().getVersion();
                    DocumentContent content = new DocumentContent();
                    content.setId(new DocumentContentId(docId, version));
                    //content.setAuthor();
                    content.setMime(contentType);
                    content.setFileName(fileName);
                    content.setRevisionDate(new Date(System.currentTimeMillis()));

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int iRead = 0;
                    byte[] buffer = new byte[4096];
                    while ((iRead = uploadedStream.read(buffer)) > 0) {
                        baos.write(buffer, 0, iRead);
                        System.out.println("\tiRead = " + iRead);
                    }
                    byte[] baResult = baos.toByteArray();
                    content.setContent(baResult);

                    session.save(content);
                    session.getTransaction().commit();
                    uploadedStream.close();
                    System.out.println("\tTransaction commited");
                }
            } else {
                out.print("No multipart");
                System.out.print("No multipart");
            }



            out.println("</body>");
            out.println("</html>");

        } catch (FileUploadException ex) {
            ex.printStackTrace();
            Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
            if (uploadedStream != null) {
                uploadedStream.close();
            }
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
